package com.ssfeng.youxia.enums;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;

/**
 * Created by liyuhang on 2020-04-28.
 */
// Enum type with constant-specific class bodies and data
public enum Operation {
    PLUS("+") {
        @Override
        public double apply(double x, double y) { return x + y; }
    },
    MINUS("-") {
        @Override
        public double apply(double x, double y) { return x - y; }
    },
    TIMES("*") {
        @Override
        public double apply(double x, double y) { return x * y; }
    },
    DIVIDE("/") {
        @Override
        public double apply(double x, double y) { return x / y; }
    };


    private final String symbol;


    Operation(String symbol) { this.symbol = symbol; }


    @Override
    public String toString() { return symbol; }


    public abstract double apply(double x, double y);

    public static void main(String[] args) {
        Optional<Operation> op = fromString("ss");
        System.out.println(op.isPresent());
    }

    // Implementing a fromString method on an enum type
    private static final Map<String, Operation> stringToEnum =
            Stream.of(values()).collect(
                    toMap(Object::toString, e -> e));

    // Returns Operation for string, if any
    public static Optional<Operation> fromString(String symbol) {
        return Optional.ofNullable(stringToEnum.get(symbol));
    }
}

